package com.imooc.springcloud.annotation;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 分布式注解切面操作
 */
@Aspect
@Slf4j
@Component
public class AccessLimiterAspect {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisScript<Boolean> rateLimitLua;

    @Pointcut("@annotation(com.imooc.springcloud.annotation.AccessLimiter)")
    public void cut() {
        log.info("cut");
    }

    @Before("cut()")
    public void before(JoinPoint joinPoint) {
        // 获得方法签名,作为methodKey
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AccessLimiter annotation = method.getAnnotation(AccessLimiter.class);
        if (annotation == null) {
            return;
        }
        String key = annotation.methodKey();
        int limit = annotation.limit();
        if (StringUtils.isEmpty(key)) {
            Class<?>[] type = method.getParameterTypes();
            key = method.getName();
            String paramTypes = Arrays.stream(type)
                    .map(Class::getName)
                    .collect(Collectors.joining(","));
            log.info("param types:{}", paramTypes);
            key += "#" + paramTypes;
        }
        // 调用redis
        boolean acquired = Boolean.TRUE.equals(stringRedisTemplate.execute(
                rateLimitLua,
                // key 列表
                Lists.newArrayList(key),
                // value 列表
                Integer.toString(limit)
        ));

        if (acquired) {
            log.error("your access is blocked, key={}", key);
            throw new RuntimeException("Your access is blocked");
        }
    }
}
